import { getCpasIcon, getFileIcon } from '@/utils/icon';
import { useState, useEffect, useRef, useCallback, useImperativeHandle } from 'react';
import TreeList, { Column, RowDragging } from 'devextreme-react/tree-list';
import { useModel } from 'umi';
import { rTime, intl, syncCpasexeFJ, fjAndDgDataCode, resDataFilter } from '@/utils';
import ErrorBounced from '@/pages/components/ErrorBounced/index';

import { LoadingBounced } from '@/pages/components/Aud/Loading';
import { delFolder, dgLinkInfoUpdParent, dgUnchain, editFolder, getAttachmentList } from './service';
import React from 'react';
import { openFile } from '@/utils/electronUtil';
import "./index.less"
import notify from 'devextreme/ui/notify';
import { Popover, Typography } from 'antd';
import Popup from 'devextreme-react/popup';
import Button from 'devextreme-react/button';
import DevDefaultPopup from '~/public/cpas-ui/components-ui/express-components/DevPopup/DevPopup';
import { deleteAttach, fjidRename, importAttachFromPlatform, replaceAttach } from '../../../../../../AuditAttach/service';
import ErrorBouncedChangeName from '@/pages/components/ErrorBounced/errorBouncedChangeName';

/**
 * 底稿附件
 * @param param0 
 * @returns 
 */

const { Text } = Typography;

const DgAttach = React.forwardRef(({ RefreshFj, dgid, fjChangeTime }: any, ref) => {
  const { initialState } = useModel('@@initialState');
  const { dbname, zcbfid, sjxmbh } = initialState?.curPart as API.CurPart;
  const { username, usercode, aesPassword } = initialState?.curUser as API.CurUser;
  const password = window.main.cryptoUtil(aesPassword);
  const [data, setData] = useState<any[]>([]);

  console.log('@@@ dgid', dgid);

  const XMType = window.sessionStorage.electronParams
    ? JSON.parse(window.sessionStorage.electronParams)?.params?.XMType
    : "单机审计项目";

  const InputDialogRef = useRef<any>(); // 模板
  const TreeListRef = useRef<any>(); // 模板

  const errorBouncedRefChangeNameRef = useRef<any>();



  const [deletePopupProps, setDeletePopupProps] = useState<{
    visible?: boolean;
    onConfirm?: () => void;
    onCancel?: () => void;
    title?: string;
    content?: string;
  }>({
    visible: false,
    onConfirm: async () => { },
    onCancel: async () => { },
    title: '',
    content: '',
  });

  const errorBouncedRef = useRef<any>(); // 错误信息对话框
  // loading panel ref
  const loadingRef = useRef<any>();

  async function getAttachList(dgidStr: string) {
    const list = await getAttachmentList(dbname, dgidStr);
    if (list.success) {
      setData(list.data);
    }
  }
  useEffect(() => {
    if (dgid) { { getAttachList(dgid) } };
  }, [dbname, fjChangeTime, dgid]);



  // 自定义方法
  // useImperativeHandle(ref, () => ({
  //   reloadList: (dgidRef: any) => {
  //     getAttachList(dgidRef);
  //   },
  // }));

  // 打开附件
  const openFjFile = useCallback((treeList: any, data: any) => {
    if (data.linkType === 0) {
      if (treeList.isRowExpanded(data.linkID)) {
        treeList.collapseRow(data.linkID);
      } else {
        treeList.expandRow(data.linkID);
      }
    } else {
      openFile([sjxmbh, zcbfid, '底稿附件', data.linkText].join('/'));
    }
  }, []);
  // 新建文件夹
  const newFolder = useCallback((parentID: string) => {
    InputDialogRef.current.show({
      title: '新建文件夹',
      value: '',
      regExpFunc: (v: any) => {
        let reg = /^[\s\S]*.*[^\s][\s\S]*$/;
        if (reg.test(v)) {
          return true;
        } else {
          notify('阶段名称不能有.后缀！', 'warning', 2000);
          return false;
        }
      },
      okCallback: async (folderName: any) => {
        const patt = new RegExp(/^\s+|\s+$/g, "")
        const result = patt.test(folderName);
        if (result) {
          notify('文件夹名称,不可为空', 'warning', 2000);
        } else {
          if (folderName) {
            const res = await editFolder({ dbname, dgid, folderName, username: username, parentID });
            if (res.success) {
              getAttachList(dgid);
              notify(intl('relationDrawer.attach.success', '操作成功'), 'success', 2000);
            } else {
              notify('新建文件夹失败', 'error', 2000);
            }
          } else {
            notify('请输入文件夹名称', 'warning', 2000);
          }
        }
      },
    });
  }, [dbname, dgid, username]);
  // 从外部导入
  const importFromDisk = async (pLinkID: string) => {
    const result = await window.electronComponents.openDialog({
      properties: ['openFile', 'multiSelections']
    });
    if (result.canceled) return;
    const res = await importAttachFromPlatform(
      result.filePaths, dbname, zcbfid, username, usercode, '1', sjxmbh, dgid, pLinkID
    );
    if (res.success) {
      const resFilter = resDataFilter(res.data);
      if (resFilter.success) {
        const { reDataArr } = resFilter;
        if (reDataArr.tempSucc.length) {
          notify('导入成功', 'success', 2000);
          getAttachList(dgid);
          RefreshFj(true);
          if (XMType === '单机审计项目') return;
          reDataArr.tempSucc.forEach((item: any) => {
            syncCpasexeFJ({
              usercode,
              password,
              zcbfid,
              BusType: 1,
              BusID: item.fj
            });
          });
        };
        if (reDataArr.tempError.length) {
          return errorBouncedRefChangeNameRef.current.show({
            args: {
              codes: true,
              dbname,
              dgnd: '',
              pupopType: 'fj',
              data: reDataArr.tempError,
            },
            okCallback: async (tempData: any[]) => {
              // console.log(tempData, '@@@ okCallback');
              if (tempData.length > 0) {
                const resUpdate = await importAttachFromPlatform(
                  tempData[1],
                  dbname,
                  zcbfid,
                  username,
                  usercode,
                  "1",
                  sjxmbh,
                  dgid,
                  pLinkID,
                  tempData[0]
                );
                if (resUpdate.success) {
                  const resFilterUpdate = resDataFilter(resUpdate.data);
                  if (resFilterUpdate.success) {
                    const { reDataArr } = resFilterUpdate;
                    if (reDataArr.tempSucc.length) {
                      notify('导入成功', 'success', 2000);
                      getAttachList(dgid);
                      RefreshFj(true);
                      if (XMType === '单机审计项目') return;
                      reDataArr.tempSucc.forEach((item: any) => {
                        syncCpasexeFJ({
                          usercode,
                          password,
                          zcbfid,
                          BusType: 1,
                          BusID: item.fj
                        });
                      });
                    };
                  }
                } else {
                  notify('导入失败', 'error', 3000);
                }
              } else {
                getAttachList(dgid);
                RefreshFj(true);
              }
            },
            cancelCallback: () => {
              // attachListRefresh();
              getAttachList(dgid);
              RefreshFj(true);
            },
          });
        }
      } else {
        notify('导入失败', 'error', 2000);
      }
    } else {
      notify('导入失败', 'error', 2000);
    }
  };

  // 数据上的右键菜单
  const relationMenuItems = function (e: any) {
    console.log(e, 'e----');
    if (e.target == 'content' && e.row?.rowType == 'data') {
      if (!e.items) { e.items = [] };
      const data: any = e.row?.data;
      console.log(data, "@@@ 附件");
      TreeListRef.current?.instance.selectRows(e.row.key);
      let tempMenus: any = [{
        icon: 'iconfont icon-dakai',
        text: intl('paper.open', '打开'),
        onItemClick: () => {
          openFjFile(e.component, data);
        }
      },
      {
        icon: 'iconfont icon-zhongmingming',
        text: intl('audit.paper.rename', '重命名'),
        onItemClick: () => {
          const linkText = data.linkText.split(".")[0];
          InputDialogRef.current.show({
            title: '重命名',
            value: linkText,
            okCallback: async (newName: any) => {
              console.log(data, '@@@');
              if (data.linkType === 0) {
                const res = await editFolder({ dbname, dgid, folderName: newName, username: username, folderID: data.linkID });
                if (res.success) {
                  // const resFilter = resDataFilter(res.data);
                  // if (resFilter.success) {
                  //   const { reDataArr } = resFilter;
                  //   if (reDataArr.tempError.length) {
                  //     const resNew = fjAndDgDataCode(reDataArr.tempError[0].code);
                  //     return notify(`${resNew}!`, 'error', 3000);
                  //   }
                  //   notify("重命名成功", "success", 2000);
                  //   getAttachList(dgid);
                  // }
                  notify("重命名成功", "success", 2000);
                  getAttachList(dgid);
                } else {
                  notify('重命名失败', 'error', 2000);
                };
              } else {
                const r = await fjidRename({ sjxmbh, dbname, zcbfid, fjid: data.fjid, rename: newName, refjlx: data.lx });
                if (r.success) {
                  const resFilter = resDataFilter(r.data);
                  if (resFilter.success) {
                    const { reDataArr } = resFilter;
                    if (reDataArr.tempError.length) {
                      const resNew = fjAndDgDataCode(reDataArr.tempError[0].code);
                      return notify(`${resNew}!`, 'error', 3000);
                    }
                    notify("重命名成功", "success", 2000);
                    getAttachList(dgid);
                  } else {
                    notify('重命名失败', 'error', 2000);
                  }
                } else {
                  notify('重命名失败', 'error', 2000);
                };
              }
            },
          });
        },
      },
      {
        icon: 'iconfont icon-delete',
        text: intl('audit.paper.del', '删除'),
        onItemClick: async () => {
          if (data.fjid) {
            setDeletePopupProps({
              visible: true,
              title: intl('audit.paper.del', '删除提醒'),
              content: "你确定要删除附件：" + data.linkText + " 吗？",
              onConfirm: async () => {
                // 设置删除弹窗
                /*const delOk = await delFolder({ dbname, folderID: data.linkID });
                if (delOk)  getAttachList(dgid), RefreshFj(true); */
                //使用附件的删除功能 add by csb 20230716
                const res = await deleteAttach([data.fjid], dbname, zcbfid, sjxmbh);
                if (res) {
                  getAttachList(dgid);
                  RefreshFj(true)

                  setDeletePopupProps({
                    visible: false,
                  });
                }
              },
              onCancel: () => {
                setDeletePopupProps({
                  visible: false,
                });
              },
            });
          } else {
            setDeletePopupProps({
              visible: true,
              title: intl('audit.paper.del', '删除提醒'),
              content: "你确定要删除此文件夹：" + data.linkText + " 吗？",
              onConfirm: async () => {
                // 设置删除弹窗
                const res = await delFolder({ dbname, folderID: data.linkID, username });
                if (res.success) {
                  getAttachList(dgid);
                  RefreshFj(true);
                  notify(intl('relationDrawer.attach.success', '操作成功'), 'success', 2000);
                } else {
                  notify('操作失败', 'error', 2000);
                }


                setDeletePopupProps({
                  visible: false,
                });
              },
              onCancel: () => {
                setDeletePopupProps({
                  visible: false,
                });
              },
            });
          }
        }
      }];
      if (data.linkType == 0) {
        tempMenus = [
          ...tempMenus,
          {
            icon: 'iconfont icon-xinjianjieduan',
            beginGroup: true,
            text: intl('relationDrawer.attach.newFolder', '新建文件夹'),
            onItemClick: () => {
              newFolder(data.linkID);
            }
          },
          {
            icon: 'importselected',
            text: intl('relationDrawer.attach.importFromDisk', '从外部导入'),
            onItemClick: async () => {
              importFromDisk(data.linkID);
            },
          },
        ];
      } else {
        tempMenus = [...tempMenus,
        {
          icon: 'iconfont icon-tihuan',
          text: intl('attach.replace', '替换'),
          onItemClick: async () => {
            const fileIDList: any[] = [];
            fileIDList.push(data.fjid);
            if (fileIDList.length === 0) {
              notify(intl('attach.replaceTo', '请选择要替换的文件'), 'error', 3000);
              return;
            }
            const result = await window.electronComponents.openFilesDialog();
            if (result.canceled) return;
            if (result.filePaths.length !== 1) {
              notify(intl('attach.replace', '请选择一个文件替换'), 'error', 3000);
              return;
            }
            const r = await replaceAttach({ filePaths: result.filePaths, fjids: fileIDList, dbname, zcbfid, sjxmbh });

            if (r.success) {
              const resFilter = resDataFilter(r.data);
              if (resFilter.success) {
                const { reDataArr } = resFilter;
                if (reDataArr.tempError.length) {
                  return errorBouncedRef.current.show({
                    args: {
                      codes: true,
                      data: reDataArr.tempError,
                    },
                  });
                }
                notify("替换文件成功", "success", 2000);
                if (dgid) { getAttachList(dgid); }
              } else {
                notify("替换文件失败", "error", 2000);
              }
            } else {
              notify("替换文件失败", "error", 2000);
            }
          },
        },
        {
          icon: 'iconfont icon-jiechuyinyong',
          text: '解除引用',
          onItemClick: async () => {
            console.log(dgid, data, '---');
            const res = await dgUnchain(dbname, dgid, data.fjid);
            if (res.success) {
              notify("解除引用成功", "success", 2000);
              if (dgid) { getAttachList(dgid); RefreshFj(true); }
            } else {
              notify("解除引用失败", "error", 2000);
            }
          },
        },
        {
          icon: 'importselected',
          beginGroup: true,
          text: intl('relationDrawer.attach.importFromDisk', '从外部导入'),
          onItemClick: async () => {
            importFromDisk(data.pLinkID);
          },
        },
        ];
      }
      e.items.push(...tempMenus);
    }
  };

  return (
    <>
      <TreeList
        ref={TreeListRef}
        className='PaperTreeList'
        dataSource={data}
        dataStructure="plain"
        rootValue=""
        keyExpr="linkID"
        parentIdExpr="pLinkID"
        displayExpr="linkText"
        selectionMode="single"
        autoExpandAll={true}
        showColumnHeaders={false}
        hoverStateEnabled={false}
        columnAutoWidth={true}
        onContextMenuPreparing={relationMenuItems}
        onRowDblClick={(e) => {
          openFjFile(e.component, e.data);
        }}
        selection={{ mode: 'single' }}
        searchPanel={{
          visible: true,
          width: 200,
          placeholder: ''
        }}
        toolbar={{
          items: [
            {
              name: 'searchPanel',
              location: 'after',
            },
            {
              location: 'after',
              text: " "
            },
            {
              location: 'after',
              widget: 'dxButton',
              cssClass: 'refreshButton_Style',
              options: {
                icon: "iconfont icon-refresh",
                onClick: async () => {
                  getAttachList(dgid);
                },
              },
            },
            {
              cssClass: 'PaperMenuItems',
              locateInMenu: 'always',
              widget: 'dxButton',
              options: {
                icon: 'iconfont icon-xinjianjieduan',
                text: intl('relationDrawer.attach.newFolder', '新建文件夹'),
                onClick: () => newFolder('')
              },
            },
            {
              cssClass: 'PaperMenuItems',
              locateInMenu: 'always',
              widget: 'dxButton',
              options: {
                icon: 'importselected',
                text: intl('relationDrawer.attach.importFromDisk', '从外部导入'),
                onClick: () => importFromDisk('')
              },
            },
          ],
        }}
      >
        <RowDragging
          allowDropInsideItem={true}
          allowReordering={true}
          showDragIcons={false}
          onDragChange={(e: any) => {
            const visibleRows = e.component.getVisibleRows();
            const sourceNode = e.component.getNodeByKey(e.itemData.linkID);
            let targetNode = visibleRows[e.toIndex].node;
            // 只有目录才接受拖放
            while (targetNode && targetNode.data) {
              if ((targetNode.data.linkID === sourceNode.data.linkID) || (targetNode.data.lx != '..')) {
                e.cancel = true;
                break;
              }
              targetNode = targetNode.parent;
            }
          }}
          onReorder={(e: any) => {
            const visibleRows = e.component.getVisibleRows();
            let sourceData = e.itemData;
            const sourceIndex = data.indexOf(sourceData);
            let newData: any = [];
            if (e.dropInsideItem) {
              sourceData = { ...sourceData, pLinkID: visibleRows[e.toIndex].key };
              // 这里要保存sourceData
              newData = [
                ...data.slice(0, sourceIndex),
                sourceData,
                ...data.slice(sourceIndex + 1),
              ];
            } else { //
              const toIndex = e.fromIndex > e.toIndex ? e.toIndex - 1 : e.toIndex;
              let targetData = toIndex >= 0 ? visibleRows[toIndex].node.data : null;
              if (targetData && e.component.isRowExpanded(targetData.ID)) {
                sourceData = { ...sourceData, pLinkID: targetData.ID };
                targetData = null;
              } else {
                const headId = targetData ? targetData.pLinkID : null;
                if (sourceData.pLinkID !== headId) {
                  sourceData = { ...sourceData, pLinkID: headId };
                }
              }
              // 这里要保存sourceData
              newData = [...data.slice(0, sourceIndex), ...data.slice(sourceIndex + 1)];
              const targetIndex = newData.indexOf(targetData) + 1;
              newData = [...newData.slice(0, targetIndex), sourceData, ...newData.slice(targetIndex)];
            }
            if (e.itemData.pLinkID != sourceData.pLinkID) {
              dgLinkInfoUpdParent(dbname, sourceData.linkID, sourceData.pLinkID);
            }
            setData(newData);
          }}
        />
        <Column
          width={368}
          dataField="linkText"
          cellRender={(cell) => {
            return <div>
              <div style={{ width: '100%', display: 'flex', justifyContent: 'left', alignItems: 'center' }}>
                {getCpasIcon(cell.data.linkType !== 0 ? cell.data.lx : '..')}
                <div style={{ width: 'calc(100% - 20px)' }}>
                  <Text style={{ width: '100%' }} ellipsis={{ tooltip: `${cell.data.fjsyh}${cell.value}` }}>
                    {cell.data.fjsyh}{cell.value}
                  </Text>
                </div>
              </div>
              {cell.data.linkType !== 0 && <div style={{ width: '100%', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div style={{ width: '45%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', color: 'rgba(102, 102, 102, 1)' }}>
                  <Text style={{ width: '100%' }} ellipsis={{ tooltip: cell.data.userName }}>
                    {cell.data.userName}
                  </Text>
                </div>
                <span style={{ color: 'rgba(102, 102, 102, 1)' }} >{rTime(cell.data.addDate)}</span>
              </div>}
            </div>
          }}
        />
      </TreeList>
      {/* <Popup
        visible={helpPanel}
        onHiding={() => {
          setHelpPanel(false);
        }}
      >
        <div>
          <h3>附件</h3>
          <p>附件是指档案中的文件，包括文本、图片、音频、视频等。</p>
          <p>附件可以在案卷中进行管理，可以对附件进行分类，可以对附件进行查询。</p>
          <h3>关系</h3>
          <p>关系是指档案中的文件，包括文本、图片、音频、视频等。</p>
          <p>关系可以在案卷中进行管理，可以对附件进行分类，可以对附件进行查询。</p>
        </div>
      </Popup> */}
      <LoadingBounced ref={loadingRef} />
      <ErrorBounced ref={errorBouncedRef} />
      <ErrorBouncedChangeName ref={errorBouncedRefChangeNameRef} />


      {/*  <DevDefaultPopup.Input ref={InputDialogRef} /> */}
      <DevDefaultPopup.Input ref={InputDialogRef} />

      <ConfirmPopup
        visible={deletePopupProps?.visible}
        // 点击确定 事件
        onConfirm={deletePopupProps?.onConfirm}
        // 点击取消 事件
        onCancel={deletePopupProps?.onCancel}
        title={deletePopupProps?.title}
        content={deletePopupProps?.content}
      />
    </>
  );
});

const ConfirmPopup = (props: {
  visible?: boolean;
  onConfirm?: () => void;
  onCancel?: () => void;
  title?: string;
  content?: string;
}) => {
  return (
    <Popup
      visible={props.visible}
      title={props?.title}
      onHiding={props?.onCancel}
      width={400}
      height={200}
      showTitle={true}
      showCloseButton={true}
      closeOnOutsideClick={true}
      contentRender={() => {
        return (
          <div>
            <div>{props?.content}</div>
            <div
              style={{
                display: 'flex',
                position: 'absolute',
                bottom: '10px',
                right: '20px',
              }}
            >
              <Button
                width={88}
                text={intl('paper.cancel', '取消')} onClick={props?.onCancel} />
              <Button
                width={88}
                type='default'
                style={{ marginRight: '10px' }}
                text={intl('paper.confirm', '确定')}
                onClick={props?.onConfirm}
              />
            </div>
          </div>
        );
      }}
    />
  );
};

export default DgAttach;
